/**
 * 
 */
package br.embedded.socialapp.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.embedded.socialapp.data.DataFacade;

/**
 * @author daniel
 *
 */
@SuppressWarnings("serial")
public class AuthServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		verifyAuth(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		verifyAuth(request, response);
	}
	
	private void verifyAuth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		boolean result = false;
		String login = request.getParameter("login");
		String passwd = request.getParameter("passwd");

		if (login != null && !login.isEmpty() && passwd != null && !passwd.isEmpty())
			result = DataFacade.getInstance().doLogin(login, passwd);
		
		writeResponse(response, result);
	}
	
	private void writeResponse(HttpServletResponse response, boolean result) throws IOException
	{
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.append("<html>");
		writer.append("<body>");

		if (result)
			writer.append("OK");
		else
			writer.append("ERROR");

		writer.append("</body>");
		writer.append("</html>");
	}
}
